/**
 * Class: mosaicPhoto
 * Use: insert preview photos mosaically into div
 * Author: Anton Syuvaev (http://h8every1.ru)
 * Date: 22.08.11
 * Version: 0.1
 */

(function($) {


    $.mosaicPhoto = {version: '0.1'};
    $.fn.mosaicPhoto = function(mp_settings) {
        mp_settings = jQuery.extend({
            _IMG: 15, /* number of images to show */
            rows: 3, /* number of rows */
            cols: 8, /* number of columns */
            imgSize: 60, /* size of an image side in pixels */
            imgMargin: 3,
            topMargin: 80,
            bottomMargin: 60,
            rightMargin:60,
            containerWidth: 60,
            totalImages: 20, /* number of images in array */
            imgType: 'weddings', /* default image type if no other is et*/
            path:'preview/',
            listeners: "#menu a"
        }, mp_settings);

        var container = this, divCount = new Array(), imgCount = new Array(), divs = new Array(), imgs = new Array();


        $(window).unbind('resize.mosaicphoto').bind('resize.mosaicphoto', function() {
            _resize_container();
        });

        $.mosaicPhoto.initialize = function() {

            settings = mp_settings;
            //#TODO: populate with real image data;

            imgCount['weddings'] = new Array();
            imgCount['portrait'] = new Array();
            imgCount['studio'] = new Array();
            for (i = 0; i < settings.totalImages; i++) {
                imgCount['weddings'][i] = i;
                imgCount['portrait'][i] = i;
                imgCount['studio'][i] = i;
            }
            
            listeners = $(settings.listeners);

            listeners.unbind('mouseover.mosaicphoto').bind('mouseover.mosaicphoto', function() {
                $.mosaicPhoto.open(this)
            });

            $.mosaicPhoto.open();
            return false;
        }

        $.mosaicPhoto.open = function(caller) {

            if (typeof settings == 'undefined') settings = mp_settings;
            if (typeof caller == 'undefined') {
                imgType = settings.imgType;
                _resize_container();
            } else {
                imgType = $(caller).attr('rel');
                _populate();
            }

        }

        function _resize_container() {
            windowHeight = $(window).height(),windowWidth = $(window).width();

            newCols = Math.floor((windowWidth * (settings.containerWidth / 100) - settings.rightMargin) / (settings.imgSize + settings.imgMargin));
            newRows = Math.floor((windowHeight - settings.bottomMargin - settings.topMargin) / (settings.imgSize + settings.imgMargin));

            if (newRows != settings.rows || newCols != settings.cols) {
                settings.rows = newRows;
                settings.cols = newCols;
                settings._IMG = Math.floor((settings.rows * settings.cols) * .27);

                if (settings._IMG > settings.totalImages) settings._IMG = settings.totalImages;

                _populate();
            }
        }

        function _populate() {
            count = 0;
            divCount = new Array();

            container.css({
                'width':settings.cols * (settings.imgSize + settings.imgMargin) + 'px',
                'height':settings.rows * (settings.imgSize + settings.imgMargin) + 'px'
            });

            container.html('');
            for (i = 0; i < settings.rows; i++) {
                for (j = 0; j < settings.cols; j++) {
                    container.append('<div class="preview" id="c' + count + '" style="width:' + settings.imgSize + 'px;height:' + settings.imgSize + 'px;top:' + (i * (settings.imgSize + settings.imgMargin)) + 'px;left:' + (j * (settings.imgSize + settings.imgMargin)) + 'px;">&nbsp;</div>');
                    divCount[count] = count;
                    count++;

                }
            }

            _changeSlide(imgType);
        }

        function _changeSlide(type) {
            if (typeof type == 'undefined') type = settings.imgType;
            imgType = type;
            $('.preview').hide().removeClass('shadowed').css('background-image', '');
            _insertImages(settings._IMG);
        }

        function _insertImages(count) {
            divs = [];
            imgs = [];
            divs = _randomFromArray(divCount, count);
            tempImgs = imgCount[imgType];
            imgs = _randomFromArray(tempImgs, count);
            _showSingle(0)
        }

        function _randomFromArray(array, count) {
            randomAry = [];
            randomAry = mosaicShuffle(array).slice(0, count);
            return randomAry;
        }

        function _showSingle(num) {
            $('#c' + divs[num])
                    .addClass('shadowed')
                    .css({'background-image':'url(' + settings.path +imgType+'/'+ imgs[num] + '.jpg)'})
                    .fadeIn(250);

            if (num < settings._IMG) {
                num++;
                _showSingle(num);
            }
        }

        function mosaicShuffle(obj) {
            var s = [];
            var ary = [];
            ary = obj.slice();
            while (ary.length) s.push(ary.splice(Math.random() * ary.length, 1)[0]);
            //while (s.length) this.push(s.pop());
            return s;
        }

        $.mosaicPhoto.initialize();
        return this; // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
    }

})(jQuery);

